import {
  LockOutlined,
  UserOutlined,
} from '@ant-design/icons';
import { message } from 'antd';
import React, { useState } from 'react';
import ProForm, { ProFormText } from '@ant-design/pro-form';
import { history, useModel } from 'umi';
import Footer from '@/components/Footer';
import styles from './index.less';
import {STATIC} from '@/services/config';
import User from '@/services/User';

/** 此方法会跳转到 redirect 参数所在的位置 */

const goto = () => {
  if (!history) return;
  setTimeout(() => {
    const { query } = history.location;
    const { redirect } = query;
    history.push(redirect || '/home/workbench');
  }, 10);
};

const Login = () => {
  const [submitting, setSubmitting] = useState(false);
  const { initialState, setInitialState } = useModel('@@initialState');
  const fetchUserInfo = async (isAdmin) => {
    const userInfo = await initialState?.fetchUserInfo?.();
    userInfo ? setInitialState({ ...initialState, currentUser: {...userInfo, isAdmin}}) : null;
  };

  const handleSubmit = async (values) => {
    try {
      setSubmitting(true);
      const { username, password } = values;
      const res = await User.login(username, password);
      message.success(STATIC.message.loginSuccess);
      await fetchUserInfo(res.isAdmin);
      goto();
      return;
    } catch (error) {
      console.error(error)
    } finally {
      setSubmitting(false);
    }
  };
  return (
    <div className={styles.container}>
      <div className={styles.main}>
        <div className={styles.title}>图书馆局端系统</div>
        <ProForm
          initialValues={{ autoLogin: true }}
          submitter={{
            searchConfig: { submitText: '登录' },
            render: (_, dom) => dom.pop(),
            submitButtonProps: {
              loading: submitting,
              size: 'large',
              style: { width: '100%' }
            }
          }}
          onFinish={async (values) => { handleSubmit(values); }}>
          <ProFormText
            name="username"
            fieldProps={{ size: 'large', prefix: <UserOutlined className={styles.prefixIcon} /> }}
            placeholder='用户名'
            rules={[{ required: true, message: '请输入用户名' }]}
          />
          <ProFormText.Password
            name="password"
            fieldProps={{ size: 'large', prefix: <LockOutlined className={styles.prefixIcon} /> }}
            placeholder='密码'
            rules={[{ required: true, message: '请输入密码' }]}
          />
        </ProForm>
      </div>
      <Footer />
    </div>
  );
};

export default Login;

